package controller;


import java.io.IOException;
import java.util.Enumeration;
import java.util.ResourceBundle;

import javax.servlet.*;
import javax.servlet.http.*;

import bean.User;

import actions.Action;
import actions.BuyAction;
import actions.CreateAktieAction;
import actions.CreateAktieBestaetigungAction;
import actions.CreateAuftragAction;
import actions.CreateUserAction;
import actions.CreateUserBestaetigungAction;
import actions.DividendeAction;
import actions.LoginAction;
import actions.LogoutAction;
import actions.SellAction;
import actions.StornoAction;
/**
 * @author Philipp Hollenstein
 * @version 10.07.2013
 */
public class FrontController extends HttpServlet {
	private static final long serialVersionUID = 1L;
       

    public FrontController() {
        super();
    }
    
    @Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
    
    
    @Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	try{

    	RequestDispatcher rd;
    	Action action = null;
    	HttpSession s = request.getSession(true);
    	String forward = null;
    	
    	if(request.getRequestURI().endsWith(".css")){
    		rd = request.getServletContext().getNamedDispatcher("default");
    		rd.forward(request, response);
    		return;
    	}
		if (request.getRequestURI().endsWith(".jsp")) {
			
			if (request.getRequestURI().contains("login")) { //Login Seite
				if (request.getParameter("login") != null) {
					if(s.getAttribute("loginFailed") == null){
						action = new LoginAction();
					}
					else if((boolean)s.getAttribute("loginFailed")){
						s.setAttribute("loginFailed", null);
					}
					else if(!(boolean)s.getAttribute("loginFailed")){
						action = new LoginAction();
					}
				}	
			}
			else{ // Falls nicht Login Seiteüberprüfung ob man eingeloggt ist
				if(s.getAttribute("loginUser") == null){ //nicht eingellogt
					forward = getForwardProperty("login");
				}
				else{ // eingeloggt				
					if (((User)s.getAttribute("loginUser")).getIsAdmin()){//eingeloggt als Admin
						if(isNormalUserPage(request)){//Falls Normale User Seite aufgerufen wird
							forward = getForwardProperty("admin");
						}
						else{
							if (request.getRequestURI().contains("createUserBestaetigung")) { 
								if (s.getAttribute("createUserFormBean") == null) {
									forward = getForwardProperty("createUser");
								}
							}
							else if (request.getRequestURI().contains("createAktieBestaetigung")) { 
								if (s.getAttribute("createAktieFormBean") == null) {
									forward = getForwardProperty("createAktie");
								}
							}
						}		
					}
					else{//nicht als Admin eingellogt
						if(isAdminPage(request)){ //Falls Adminseite aufgerufen wird
							forward = getForwardProperty("myPortfolio"); //weiterleitung zur User-Startseite
						}
						else{
							if (request.getRequestURI().contains("createAuftrag")) { 
								if (request.getAttribute("aktienName") == null) {
									forward = getForwardProperty("myPortfolio");
								}
							}
						}
					}	
				}
			}
		}
		// TODO Abfrage der Actions verändern
		/* Diese Abfrage sollten noch verändert werden. So dass die Action anhand eines zusammengesetzten Strings
		 * aufgerufen werden, welche der Key einer Map ist. Die Actions werden in der init() Methode instanziert.
		 * So werden auch nicht unmengen an Action-Objekte erstellt, denn man braucht für jede Action ja nur eines.
		 * Die Value beinhaltet dann das jeweilige Action Objekt, welche anhand des Keys aufgerufen wird.
		 * Zum Beispiel so: 1. init:  actionMap.put("meineAction", mdAction); 
		 * 					2. Aufruf: Action actionObject = actionMap.get("meineAction"); */
		else if(request.getRequestURI().endsWith(".do")){	
			if(request.getParameterMap().size() > 0){
				if (request.getRequestURI().contains("login")) {
					if (request.getParameter("login") != null) {
						if(s.getAttribute("loginFailed") == null){
							action = new LoginAction();
						}
						else if((boolean)s.getAttribute("loginFailed")){
							s.setAttribute("loginFailed", null);
						}
						else if(!(boolean)s.getAttribute("loginFailed")){
							action = new LoginAction();
						}
					}
				}
				
				else if (request.getRequestURI().contains("createUser")) {
					if (request.getParameter("createUser") != null) {
						action = new CreateUserAction();
					}
					else if (request.getParameter("createUserBestaetigung") != null) {
						action = new CreateUserBestaetigungAction();
					}
					else if (request.getParameter("back") != null) {
						forward = getForwardProperty("createUser");
					}
				}
				
				else if (request.getRequestURI().contains("createAktie")) {
					if (request.getParameter("createAktie") != null) {
						action = new CreateAktieAction();
					}
					else if (request.getParameter("createAktieBestaetigung") != null) {
						action = new CreateAktieBestaetigungAction();
					}
					else if (request.getParameter("back") != null) {
						forward = getForwardProperty("createAktie");
					}
				}
				else if(request.getRequestURI().contains("sell")){
					if(request.getParameter("sell") != null){
						action = new SellAction();
					}
				}
				else if(request.getRequestURI().contains("buy")){
					if(request.getParameter("buy") != null){
						action = new BuyAction();
					}
				}
				else if(request.getRequestURI().contains("storno")){
					if(request.getParameter("storno") != null){
						action = new StornoAction();
					}
				}
				else if(request.getRequestURI().contains("createAuftrag")){
					if(request.getParameter("createAuftrag") != null){
						action = new CreateAuftragAction();
					}
					else if (request.getParameter("back") != null) {
						forward = getForwardProperty("myPortfolio");
					}
				}
				else if(request.getRequestURI().contains("dividende")){
					if(request.getParameter("ausschuetten") != null){
						action = new DividendeAction();
					}
					else if (request.getParameter("back") != null) {
						forward = getForwardProperty("admin");
					}
				}
				else if(request.getRequestURI().contains("logout")){
					if(request.getParameter("logout") != null){
						action = new LogoutAction();
					}
				}
				else{ 
					forward = getForwardProperty("error");
				}
			}
			else{ // falls es keine übermittelten Parameters gibt oder eine unbekannte Action aufgerufen wird(z.B. asdfas.do)
				forward = getForwardProperty("myPortfolio");
			}
				
		}
		else{
			forward = getForwardProperty("error");
		}

		
		
		if(action != null || forward != null){
			if(forward == null){
				forward = action.execute(request, s);
			}
			rd = getServletContext().getRequestDispatcher(forward);
		}
		else{
			rd = forwardWithNamedDispatcher(request, response);
		}
		rd.forward(request, response);
		
		
    	} catch(Exception e){
    		e.printStackTrace();
    	}
		
		
	}
    
    
    private RequestDispatcher forwardWithNamedDispatcher(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
    	RequestDispatcher rd = getServletContext().getNamedDispatcher("jsp");
    	return rd;
    }
    
    private boolean isAdminPage(HttpServletRequest request){// TODO in Property file auslagern
    	if(request.getRequestURI().contains("admin"))
    		return true;
    	else if (request.getRequestURI().contains("createUser"))
    		return true;
    	else if (request.getRequestURI().contains("createAktie"))
    		return true;
    	else
    		return false;
    }
    
    
    private boolean isNormalUserPage(HttpServletRequest request){// TODO in Property file auslagern
    	if(request.getRequestURI().contains("myPortfolio"))
    		return true;
    	else if (request.getRequestURI().contains("offeneAuftraege"))
    		return true;
    	else if (request.getRequestURI().contains("createAuftrag"))
    		return true;
    	else
    		return false;
    }
    
    private String getForwardProperty(String keyWord) throws IOException{
		return ResourceBundle.getBundle("properties.forward").getString(keyWord);
	}	

}
